/**
 * 格式化日期 - formatTime
 * @param [data] date 时间对象
 * @returns [string] 2017/05/16 00:29:53
*/
var addZero = function (n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
var typeCheck = {
  isDef: function (value) {
    return value !== undefined
  },
  isArr(value) {
    return Object.prototype.toString.call(value) === '[object Array]'
  },
  isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]'
  },
  isFun: function (value) {
    return typeof value === 'function'
  },
  isObj: function (value) {
    return Object.prototype.toString.call(value) === '[object Object]'
  },
  isNum: function (value) {
    return (typeof value === 'number') && isFinite(value)
  },
  isBool: function (value) {
    return typeof value === 'boolean'
  },
  isStr: function (value) {
    return typeof value === 'string'
  }
}

export function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(addZero).join('/') + ' ' + [hour, minute, second].map(addZero).join(':')
}

export function formatDate(date, format) {
  if (!typeCheck.isDef(date) || !typeCheck.isDate(date)) return date
  var fmap = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S+': date.getMilliseconds()
  }
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in fmap) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? fmap[k] : ('00' + fmap[k]).substr(('' + fmap[k]).length))
    }
  }
  return format
}

export function compareVersion(a, b) {
  var as = a.split('.');
  var bs = b.split('.');
  if (a === b) return 0;

  for (var i = 0; i < as.length; i++) {
    var x = parseInt(as[i]);
    if (!bs[i]) return 1;
    var y = parseInt(bs[i]);
    if (x < y) return -1;
    if (x > y) return 1;
  }
}